﻿namespace MicroCloud.Utils
{
    #region "MacOS平台命令执行器"
    /// <summary>
    /// MacOS平台命令执行器
    /// </summary>
    [SupportedOSPlatform("macos")]
    public static class MacOSCommandExecutor
    {
        private static readonly string[] fileExtArray = [".sh", ".bash"];

        #region "静态方法"
        #region "执行命令并获取输出结果"
        /// <summary>
        /// 执行命令并获取输出结果
        /// </summary>
        /// <param name="command">命令字符串</param>
        /// <returns>输出结果</returns>
        public static string ExecuteCommand(string command)
        {
            var escapedArgs = command.Replace("\"", "\\\"");
            ProcessStartInfo startInfo = new()
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                //RedirectStandardError = true,
                CreateNoWindow = true,
                FileName = "/bin/bash", // 使用 bash
                // FileName = "/bin/sh", // 使用 sh
                Arguments = $"-c \"{escapedArgs}\"",

            };
            Process process = new()
            {
                StartInfo = startInfo
            };

            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            return output;
        }
        #endregion
        #region "执行命令文件并获取输出结果"
        /// <summary>
        /// 执行命令文件并获取输出结果
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <returns>输出结果</returns>
        public static string ExecuteCommandFile(string fileName)
        {
            Check.FileExists(fileName, nameof(fileName));
            string ext = Path.GetExtension(fileName);
            if (!fileExtArray.Any(m => m.Equals(ext, StringComparison.OrdinalIgnoreCase)))
            {
                throw new ArgumentException(I18N.T("文件名必须以“.sh，.bash”结尾"));
            }

            var startInfo = new ProcessStartInfo
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                //RedirectStandardError = true,
                CreateNoWindow = true,
                FileName = fileName,
            };
            Process process = new()
            {
                StartInfo = startInfo
            };

            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            return output;
        }
        #endregion

        #endregion

    }
    #endregion

}
